package com.self.av;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.OpenableColumns;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private static final int PERMISSION_REQUEST_READ_EXTERNAL_STORAGE = 1;
    private static final int PERMISSION_REQUEST_CAMERA = 2;
    private static final int REQUEST_CODE_SELECT_VIDEO = 1;
    private static final String SOURCE_KEY = "videoSource";
    private static final String SOURCE_LOCAL = "local";
    private static final String SOURCE_RECORD = "record";
    private TextView updateTextView;
    private Button analyzeLocalVideoButton;
    private Button compareLocalVideoButton;
    private RadioGroup modelSelectionRadioGroup;
    private RadioGroup modelCompareRadioGroup;

    // 注册权限请求回调
    private final ActivityResultLauncher<String> requestReadStoragePermissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
                if (isGranted) {
                    // 用户授予了权限，启动选择视频的意图
                    openVideoSelector();
                } else {
                    // 用户拒绝了权限，给出相应提示
                    Toast.makeText(this, "读取外部存储权限被拒绝，无法选择视频", Toast.LENGTH_SHORT).show();
                }
            });


    // 注册启动 Activity 回调
    private final ActivityResultLauncher<Intent> startVideoSelectorLauncher =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
                if (result.getResultCode() == RESULT_OK) {
                    Intent data = result.getData();
                    if (data != null) {
                        Uri uri = data.getData();
                        if (uri != null) {
                            ContentResolver contentResolver = getContentResolver();
                            // 获取文件名
                            String fileName = Utils.getFileName(contentResolver, uri);
                            // 直接传递 Uri 到 VideoPlayerActivity 并传入本地视频标识
                            Intent playerIntent = new Intent(this, VideoPlayerActivity.class);
                            playerIntent.putExtra("videoUri", uri.toString());
                            playerIntent.putExtra(SOURCE_KEY, SOURCE_LOCAL);
                            // 获取选中的 RadioButton 的值
                            int selectedId = modelSelectionRadioGroup.getCheckedRadioButtonId();
                            RadioButton selectedRadioButton = findViewById(selectedId);
                            String selectedModel = selectedRadioButton.getText().toString();
                            playerIntent.putExtra("selectedModel", selectedModel.trim());

                            startActivity(playerIntent);
                        }
                    }
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 获取版本号
        String versionName = BuildConfig.VERSION_NAME;
        TextView versionTextView = findViewById(R.id.versionTextView);
        versionTextView.setText("当前版本号: " + versionName);

        // 为跳转按钮设置点击事件
        Button goToReleasesButton = findViewById(R.id.goToReleasesButton);
        goToReleasesButton.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://gitee.com/self6789/ArcheryVision/releases"));
            startActivity(intent);
        });

        SharedPreferences prefs = getSharedPreferences("VideoPlayerPrefs", MODE_PRIVATE);
        String selectedModel = prefs.getString("selectedModel", null);
        modelSelectionRadioGroup = findViewById(R.id.modelSelectionRadioGroup);
        if (selectedModel != null) {
            int childCount = modelSelectionRadioGroup.getChildCount();
            for (int i = 0; i < childCount; i++) {
                View child = modelSelectionRadioGroup.getChildAt(i);
                if (child instanceof RadioButton) {
                    RadioButton radioButton = (RadioButton) child;
                    if (radioButton.getText().toString().equals(selectedModel)) {
                        radioButton.setChecked(true);
                        break;
                    }
                }
            }
        }

        String selectedModelCompare = prefs.getString("selectedModelCompare", null);
        modelCompareRadioGroup = findViewById(R.id.modelCompareRadioGroup);
        if (selectedModelCompare != null) {
            int childCount = modelCompareRadioGroup.getChildCount();
            for (int i = 0; i < childCount; i++) {
                View child = modelCompareRadioGroup.getChildAt(i);
                if (child instanceof RadioButton) {
                    RadioButton radioButton = (RadioButton) child;
                    if (radioButton.getText().toString().equals(selectedModelCompare)) {
                        radioButton.setChecked(true);
                        break;
                    }
                }
            }
        }

        // 发起网络请求获取最新版本号
        getLatestVersion(goToReleasesButton, versionName);

        analyzeLocalVideoButton = findViewById(R.id.analyzeLocalVideoButton);
        compareLocalVideoButton = findViewById(R.id.compareLocalVideoButton);
        updateTextView = findViewById(R.id.updateTextView);

//        analyzeRecordVideoButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                // 检查是否已经授予摄像机权限
//                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
//                        != PackageManager.PERMISSION_GRANTED) {
//                    // 如果没有授予权限，则请求权限
//                    ActivityCompat.requestPermissions(MainActivity.this,
//                            new String[]{Manifest.permission.CAMERA},
//                            PERMISSION_REQUEST_CAMERA);
//                } else {
//                    // 已经授予权限，启动 VideoPlayerActivity 并传入录制视频标识
//                    startVideoPlayerWithRecordSource();
//                }
//            }
//        });

        analyzeLocalVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String permission = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
                        ? Manifest.permission.READ_MEDIA_VIDEO
                        : Manifest.permission.READ_EXTERNAL_STORAGE;
                // 检查是否已经授予读取外部存储的权限
                if (ContextCompat.checkSelfPermission(MainActivity.this, permission)
                        != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有授予权限，则请求权限
                    requestReadStoragePermissionLauncher.launch(permission);
                } else {
                    // 已经授予权限，可以启动选择视频的意图
                    openVideoSelector();
                }
            }
        });
        compareLocalVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent playerIntent = new Intent(getApplicationContext(), VideoCompareActivity.class);
//                    playerIntent.putExtra("videoUri", uri.toString());
                playerIntent.putExtra(SOURCE_KEY, SOURCE_LOCAL);
                // 获取选中的 RadioButton 的值
                int selectedId = modelSelectionRadioGroup.getCheckedRadioButtonId();
                RadioButton selectedRadioButton = findViewById(selectedId);
                String selectedModel = selectedRadioButton.getText().toString();
                playerIntent.putExtra("selectedModel", selectedModel.trim());
                int selectedIdCompare = modelCompareRadioGroup.getCheckedRadioButtonId();
                RadioButton selectedRadioButtonCompare = findViewById(selectedIdCompare);
                String selectedModelCompare = selectedRadioButtonCompare.getText().toString();
                playerIntent.putExtra("selectedModelCompare", selectedModelCompare.trim());
                startActivity(playerIntent);
            }
        });
    }

    private void getLatestVersion(Button goToReleasesButton, String versionName) {
        OkHttpClient client = new OkHttpClient();
        // 替换为实际的 API 接口地址
        Request request = new Request.Builder()
                .url("https://gitee.com/self6789/ArcheryVision/releases")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                new Handler(Looper.getMainLooper()).post(() -> {
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String content = response.body().string();
                    String regex = "<div class='tag-name' data-tag-name='(\\d+?)'>";
                    String regexDesc = "<textarea class='content' style='display:none;'>(.+?)</textarea>";
                    Pattern pattern = java.util.regex.Pattern.compile(regex);
                    Pattern patternDesc = java.util.regex.Pattern.compile(regexDesc);
                    Matcher matcher = pattern.matcher(content);
                    Matcher matcherDesc = patternDesc.matcher(content);

                    if (matcher.find()) {
                        String versionStr = matcher.group(1);
                        new Handler(Looper.getMainLooper()).post(() -> {
                            try {
                                int lastestVersion = Integer.parseInt(versionStr);
                                int currentVersion = Integer.parseInt(versionName);
                                if (lastestVersion > currentVersion) {
                                    goToReleasesButton.setText("有新版本：" + lastestVersion);
                                    if (matcherDesc.find()) {
                                        String desc = matcherDesc.group(1);
                                        try{
                                            Spanned decodedText;
                                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                                                // 第二个参数表示解析时的 flags，0 为默认
                                                decodedText = Html.fromHtml(desc, 0);
                                            } else {
                                                // 兼容低版本（API < 24）
                                                decodedText = Html.fromHtml(desc);
                                            }
                                            new Handler(Looper.getMainLooper()).post(() -> {
                                                updateTextView.setText(decodedText);
                                            });
                                        }catch (Exception e){
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            } catch (NumberFormatException e) {
                            }
                        });
                    }


                } else {
//                    new Handler(Looper.getMainLooper()).post(() -> {
//                    });
                }
            }
        });
    }

    private void startVideoPlayerWithRecordSource() {
        Intent playerIntent = new Intent(MainActivity.this, CameraAnalysisActivity.class);
        playerIntent.putExtra(SOURCE_KEY, SOURCE_RECORD);
        startActivity(playerIntent);
    }

    private void openVideoSelector() {
        // 使用 Intent.ACTION_PICK 打开系统相册选择视频
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("video/*");
        startVideoSelectorLauncher.launch(intent);
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
//                                           @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (requestCode == PERMISSION_REQUEST_READ_EXTERNAL_STORAGE) {
//            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                // 用户授予了权限，启动选择视频的意图
//                openVideoSelector();
//            } else {
//                // 用户拒绝了权限，给出相应提示
//                Toast.makeText(this, "读取外部存储权限被拒绝，无法选择视频", Toast.LENGTH_SHORT).show();
//            }
//        }
//    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == REQUEST_CODE_SELECT_VIDEO && resultCode == RESULT_OK) {
//            Uri uri = data.getData();
//            if (uri != null) {
//                ContentResolver contentResolver = getContentResolver();
//                // 获取文件名
//                String fileName = getFileName(contentResolver, uri);
//                // 直接传递 Uri 到 VideoPlayerActivity 并传入本地视频标识
//                Intent playerIntent = new Intent(this, VideoPlayerActivity.class);
//                playerIntent.putExtra("videoUri", uri.toString());
//                playerIntent.putExtra(SOURCE_KEY, SOURCE_LOCAL);
//                startActivity(playerIntent);
//            }
//        }
//    }

}